import threading

from module.data.TickerSimulater import PushTickerSimulater
from module.data.PreTickerHandler import preTickerHandler

from module.const.Constant import const
from module.thread.SimulatThread import SimulatThread

import logging
log = logging.getLogger('tasklog')

def getRelatedStocks(shortOptionDetail):
    relatedStocks = set()
    buyItemList = eval(shortOptionDetail['buyItemList'][0])
    for one in buyItemList:
        if "个股对比" in one['aItem']:
            relatedStocks.add(one['bItem'])
    sellItemList = eval(shortOptionDetail['sellItemList'][0])
    for one in sellItemList:
        if "个股对比" in one['aItem']:
            relatedStocks.add(one['bItem'])
    stopItemList = eval(shortOptionDetail['stopItemList'][0])
    for one in stopItemList:
        if "个股对比" in one['aItem']:
            relatedStocks.add(one['bItem'])
    log.info("策略任务匹配到个股对比： 关联个股-%s 策略详情-%s" % (relatedStocks, shortOptionDetail))
    return relatedStocks



class DataSimulatThread(threading.Thread):
    def __init__(self, taskcenter):
        threading.Thread.__init__(self)
        self.taskid = taskcenter[0]['taskid']
        self.taskCenter = taskcenter

    def run(self):
        index = 0
        currTask = self.taskCenter[2][0]
        log.info("任务启动行情推送主线程: taskid - %s" % self.taskid)
        while index < len(self.taskCenter[2]):
            try:
                currTask = self.taskCenter[2][index]
                # 任务手动暂停判断
                if self.taskCenter[1] == const.TASK_STATUS_STOP and currTask[4] == const.TASK_STATUS_STOP:
                    log.info("%s任务 DataSimulatThread触发手动暂停 详情信息：%s" % (self.taskid, self.taskCenter))
                    break
                # 任务异常判断
                if self.taskCenter[1] == const.TASK_STATUS_EXCEPT and currTask[4] == const.TASK_STATUS_EXCEPT:
                    log.info("%s任务 DataSimulatThread触发异常暂停 详情信息：%s" % (self.taskid, self.taskCenter))
                    break

                # 策略任务 日数据列表子任务状态
                if self.taskCenter[1] == const.TASK_STATUS_LOADING or self.taskCenter[1] == const.TASK_STATUS_RUNNING:
                    currTask[4] = const.TASK_STATUS_RUNNING
                    log.info("行情推送主线程： taskid - %s 开始推送日期任务： %s" % (self.taskid, currTask))

                    relatedStocks = getRelatedStocks(self.taskCenter[0])
                    datadate = currTask[1]
                    starttime = currTask[2]
                    endtime = currTask[3]
                    if not relatedStocks:
                        code = currTask[0]
                        log.info("行情推送主线程（无个股对比）： taskid - %s 开推送日期任务： %s" % (self.taskid, currTask))
                        tickerData = preTickerHandler(code, datadate, starttime, endtime)
                        if tickerData:
                            log.info("%s任务持续运行: 任务信息-%s 加载数据-%s" % (self.taskid, currTask, len(tickerData)))
                            simulater = PushTickerSimulater(self.taskCenter[0]['uuid'], self.taskCenter[0]['taskid'])
                            simulater.ticker_data_push(currTask, tickerData)
                        else:
                            log.info("%s任务持续运行: 任务信息-%s 无数据" % (self.taskid, currTask))
                    else:
                        log.info("行情推送主线程（个股对比）: taskid-%s 主股任务信息-%s" % (self.taskid, currTask))
                        threadMain = SimulatThread(self.taskid, currTask)
                        threadMain.start()

                        threadSeconds = []
                        for one in relatedStocks:
                            # 个股配置格式 "bItem":"小鹏汽车,US.XPEV"
                            stockname = one.split(",")[0]
                            stockcode = one.split(",")[1]
                            newTaskDetail = [stockcode, datadate, starttime, endtime, 0, stockname]
                            log.info("个股对比单独任务: taskid-%s 关联股任务信息-%s" % (self.taskid, newTaskDetail))
                            threadSub = SimulatThread(self.taskid, newTaskDetail)
                            threadSub.start()
                            threadSeconds.append(threadSub)

                        threadMain.join()
                        for onethread in threadSeconds:
                            onethread.join()
                    # 执行完成
                    if self.taskCenter[1] == const.TASK_STATUS_RUNNING:
                        # 策略任务日任务执行完成
                        currTask[4] = const.TASK_STATUS_DONE
                index += 1
            except Exception as err:
                log.error("任务持续运行异常:%s 任务信息：%s" % (err, currTask))
                # 策略任务启动异常
                self.taskCenter[1] = const.TASK_STATUS_EXCEPT
                # for minitask in self.taskCenter[2]:
                #     if minitask[4] == const.TASK_STATUS_LOADING or minitask[4] == const.TASK_STATUS_RUNNING:
                #         minitask[4] = const.TASK_STATUS_EXCEPT
                # break

        if self.taskCenter[1] == const.TASK_STATUS_RUNNING:
            # 策略任务执行完成
            self.taskCenter[1] = const.TASK_STATUS_DONE
